#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import datetime


class NeimengguByneswyxrmzf5a5fPolicy(BaseTaxPolicySpider):
    name = 'neimenggu_byneswyxrmzf_5a5f_policy'

    source = '巴彦淖尔市五原县人民政府'
    province = '内蒙古自治区'
    city = '巴彦淖尔市'
    county = '五原县'
    park = ''
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
    }

    def start_requests(self):
        url = 'http://www.wuyuan.gov.cn/xxyxgfxwjk/index.html'
        url = "http://www.wuyuan.gov.cn/rmt/a/api/zwgk/files/findFilesList"
        data = {
            "siteId": "f4f8152cf0cd47c0a69f16be6bce423f",
            "type": "0",
            "keyword": "",
            "topicClassId": "",
            "publishAgency": "all",
            "docNumber": "",
            "inputTime": "",
            "inputTimeEnd": "",
            "publishTime": "",
            "publishTimeEnd": "",
            "pageSize": "10",
            "pageNo": "1"
        }
        # data = json.dumps(data, separators=(',', ':'))
        yield scrapy.FormRequest(url, method='POST', formdata=data, callback=self.parse_list, meta={"data": data},
                                 headers=self.headers)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.json()['data']:
            item = Item()
            item['source_url'] = elem['docurl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = datetime.datetime.fromtimestamp(elem['inputTime'] / 1000)
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            data = response.meta.get('data')
            total_page = response.json()['allPage']
            for page_num in range(2, int(total_page) + 1):
                data['pageNo'] = page_num
                yield response.follow(response.url, body=data, callback=self.parse_list, headers=self.headers,
                                      meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl neimenggu_byneswyxrmzf_5a5f_policy".split())
